import React, { useState, useRef } from "react";
import { useTranslation } from "react-i18next";
import { InputNumber, Slider, Divider, Input, Button, Tooltip } from "antd";
import GrayTipIcon from "../../../../assets/images/dapp/gray_tips.svg";
import TransIcon from "../../../../assets/images/dapp/trans.png";
import USTDIcon from "../../../../assets/images/dapp/ustd.svg";
import ESTDIcon from "../../../../assets/images/dapp/estd.svg";
import {BuyDetailRecords} from "./buyDetailRecords.js";
import {SellDetailRecords} from "./sellDetailRecords.js";
import DealChangeIcon from '../../../../assets/images/dapp/dealChange.svg'
import AddAddressIcon from '../../../../assets/images/dapp/addAddress.svg'
export const DealBox = React.forwardRef(({headerType}, ref)  => {

  const { t } = useTranslation();
  const buyDetailRecordsRef = useRef();
  const sellDetailRecordsRef = useRef();
  const [topCoin, setTopCoin] = useState("USDT");
  const [bottomCoin, setBottomCoin] = useState("ESTD");
  const [percentValue, setPercentValue] = useState(0);
  const [sliderChanged, setSliderChanged] = useState(false);
  const [currentPriceObj, setCurrentPriceObj] = useState({
    price: 1976.87293425,
    rate: "1%",
    fee: "...",
    max: 20000,
    rateSell: '2%'
  });

  const [addingAddress, setAddingAddress] = useState(false); // 是否添加地址
  const [inputValue, setInputValue] = useState(null);
  const [progressVisible, setProgressVisible] = useState(false);
  const [transFerType, setTransFerType] = useState(0); // 0-转入，1-转出
  const [receivedValue, setReceivedValue] = useState(null); // received的值
  const [distructionValue, setDistructionValue] = useState(null); // destruction的值

  const [mintValue, setMintValue] = useState(null); // mint的值

  const handleTrans = () => {
    setTransFerType(transFerType == 0 ? 1 : 0);
  };
  const middleTitle = (
    <div className="middle-title" onClick={() => handleTrans()}>
      <img src={TransIcon} className="trans-icon"></img>
    </div>
  );

  // 获取输入框的值
  const handleGetInputValue = (e) => {
    setInputValue(e);
    let num = e
    if(e > currentPriceObj.max) {
      num = currentPriceObj.max;
    }
    let value = parseFloat(num / currentPriceObj.price).toFixed(4);
    setMintValue(value);


  };

  const handleChangeMintValue = (e) => {
    setMintValue(e);
    let value = parseFloat(e * currentPriceObj.price).toFixed(8);

    if(value > currentPriceObj.max) {
      value = currentPriceObj.max;
      let newMintValue = parseFloat(value / currentPriceObj.price).toFixed(4);
      setMintValue(newMintValue);
  
    }
    setInputValue(value);
  }

  const handleSetProgress = () => {
    console.log("handleSetProgress");
    setProgressVisible(false);
  };

  // 改变slider的值
  const handleChangeSilder = (val) => {
    setPercentValue(val);
    if (val != 25 && val != 50 && val != 75 && val != 100) {
      setSliderChanged(true);
    } else {
      setSliderChanged(false);
    }
  };

  // 聚焦输入框显示进度条
  const handleShowProgress = () => {
    setProgressVisible(true);
  };

  // 获取received的值
  
  const handleGetReceivedValue = (e) => {
    console.log("handleGetReceivedValue", e);
    setDistructionValue(e);
    let value  = parseFloat(e / currentPriceObj.price).toFixed(4);

    if(e > currentPriceObj.max) { 
      value = currentPriceObj.max;
      let newDistructionValue = parseFloat(value / currentPriceObj.price).toFixed(4);
      setDistructionValue(newDistructionValue);

    }
    setReceivedValue(value);

  }


  // 获取distruction的值
  const handleGetDistructionValue = (e) => {
    console.log("handleGetDistructionValue", e);
    let value  = parseFloat(e * currentPriceObj.price).toFixed(8);

    if(value > currentPriceObj.max) {

      value = currentPriceObj.max;
      let newReceivedValue = parseFloat(value / currentPriceObj.price).toFixed(4);
      setReceivedValue(newReceivedValue);
    }
    setDistructionValue(value);
  }

  const handleSetMax = (val) => {

    if(headerType == 0) {
      setInputValue(currentPriceObj.max);
      let value = parseFloat(currentPriceObj.max / currentPriceObj.price).toFixed(4);
      setMintValue(value);
    } else {
      setDistructionValue(currentPriceObj.max);
      let value = parseFloat(currentPriceObj.max / currentPriceObj.price).toFixed(4);
      setReceivedValue(value);
    }
    
  }

  const handleBtnClick = () => {
    if(headerType == 0) {
      buyDetailRecordsRef.current.open()
    } else {
      sellDetailRecordsRef.current.open()
    }
  }

  


  return (
    <div className="deal-box-comp">
      {headerType == 0 ? (

        // buy
        <div className="deal-trans-box">
          <div className="box-control top-box">
            <div className="box-title">
              <div className="title-text">{t("dappDeal.pay")}</div>
              <div className="title-right">
                <div className="right-value">{parseFloat(currentPriceObj.max).toFixed(8)}</div>
                <div className="right-max" onClick={() => handleSetMax()}>Max</div>
              </div>
            </div>
            <div className="box-info">
              <InputNumber
                className="value-input"
                placeholder="0.00000000"
                min={0}
                max={currentPriceObj.max}
                value={inputValue}
                onChange={(e) => handleGetInputValue(e)}
                // onFocus={() => handleShowProgress()}
                // onBlur={() => handleSetProgress()}
              />
              <div className="coin-info">
                <div className="coin-icon">
                  <img src={USTDIcon} alt="" />
                </div>
                <div className="coin-name">USDT</div>
              </div>
            </div>
            {progressVisible ? (
              <div className="fast-box">
                <div className="percent-row">
                  <div className={percentValue == 25 ? "active" : "normal"}>
                    25%
                  </div>
                  <div className={percentValue == 50 ? "active" : "normal"}>
                    50%
                  </div>
                  <div className={percentValue == 70 ? "active" : "normal"}>
                    75%
                  </div>
                  <div className={percentValue == 100 ? "active" : "normal"}>
                    100%
                  </div>
                  <div
                    className={
                      sliderChanged ? "slider-active" : "slider-normal"
                    }
                  >
                    {percentValue}

                    <span className="unit">%</span>
                  </div>
                </div>
                <div className="slider-row">
                  <Slider
                    defaultValue={percentValue}
                    className="slider-control"
                    onChangeComplete={(val) => handleChangeSilder(val)}
                  />
                </div>
              </div>
            ) : null}
          </div>
          <div className="middle-box">
            <Divider children={middleTitle} />
          </div>
          <div className="box-control bottom-box">
            <div className="box-title">
              <div className="title-text">{t("dappDeal.cast")}</div>
              <div className="title-right">
                <div className="right-value">--</div>
              </div>
            </div>
            <div className="box-info">
              <InputNumber min={0} className="value-input" placeholder="0" value={mintValue} onChange={handleChangeMintValue}/>
              <div className="coin-info">
                <div className="coin-icon">
                  <img src={ESTDIcon} alt="" />
                </div>
                <div className="coin-name">ESDT</div>
              </div>
            </div>
          </div>
        </div>
      ) : (
        <div className="deal-trans-box">
          <div className="box-control top-box">
            <div className="box-title">
              <div className="title-text">{t("dappDeal.destruction")}</div>
              <div className="title-right">
                <div className="right-value">{parseFloat(currentPriceObj.max).toFixed(8)}</div>
                <div className="right-max" onClick={() => handleSetMax()}>Max</div>
              </div>
            </div>
            <div className="box-info">
              <InputNumber
                className="value-input"
                placeholder="0.00000000"
                min={0}
                max={currentPriceObj.max}
                value={distructionValue}
                onChange={(e) => handleGetReceivedValue(e)}
                onFocus={() => handleShowProgress()}
                onBlur={() => handleSetProgress()}
              />

              <div className="coin-info">
                <div className="coin-icon">
                  <img src={ESTDIcon} alt="" />
                </div>
                <div className="coin-name">ESDT</div>
              </div>
               
          
          </div>
       
          </div>
          <div className="middle-box">
            <Divider children={middleTitle} />
          </div>
          <div className="box-control bottom-box">
            <div className="box-title">
              <div className="title-text">{t("dappDeal.received")}
                <div className="recevied-model-change">
                  <div className="change-text">{t("dappDeal.cashSellTag")}</div>
                  <img src={DealChangeIcon} className="change-icon"></img>
                </div>
              </div>
              <div className="title-right">
                <div className="right-value">--</div>
              </div>
            </div>
            <div className="box-info">
              <InputNumber min={0} className="value-input" placeholder="0" value={receivedValue} onChange={handleGetDistructionValue}/>
              <div className="coin-info">
                <div className="coin-icon">
                  <img src={USTDIcon} alt="" />
                </div>
                <div className="coin-name">USDT</div>
              </div>
              </div>
            </div>
        </div>
      )}
    
      {addingAddress ? (
        <div
          className="adding-address"
          onClick={() => {
            setAddingAddress(false);
          }}
        >
          {t("dappDeal.removeAddress")}
        </div>
      ) : (
        <div
          className="add-address"
          onClick={() => {
            setAddingAddress(true);
          }}
        >
         <img src={AddAddressIcon} className="prev-icon"></img> {t("dappDeal.addAddress")}
        </div>
      )}

      {addingAddress ? (
        <div className="address-save-box">
          <div className="title-row">
            <div className="label-text">{t("dappDeal.addressSaveLable")}</div>
            <div className="tips-text">{t("dappDeal.addressSaveTips")}</div>
          </div>
          <Input className="address-input"></Input>
        </div>
      ) : null}

      <div className="current-price-box">
        <div className="current-price-row">
          <div className="label-text">
            <Tooltip
              title={t("dappDeal.currentPriceTip")}
              color={"#2B2C33"}
              placement="rightBottom"
            >
              <img src={GrayTipIcon} alt="" className="tip-icon" />
            </Tooltip>
            {t("dappDeal.currentPriceLabel")}
          </div>
          <div className="value-text">{currentPriceObj.price}</div>
        </div>
        <div className="other-fee-row">
          <div className="label-text">
            <Tooltip
              title={headerType == 0 ? t("dappDeal.dealServiceTip"):t("dappDeal.dealSellServiceTip") }
              color={"#2B2C33"}
              placement="rightBottom"
            >
              <img src={GrayTipIcon} alt="" className="tip-icon" />
            </Tooltip>

            {t("dappDeal.commissionText")}
          </div>
          <div className="value-text">{headerType == 0 ? currentPriceObj.rate : currentPriceObj.rateSell}</div>
        </div>
        <div className="other-fee-row">
          <div className="label-text">
            <Tooltip
              title={t("dappDeal.absenteeismFeesTip")}
              color={"#2B2C33"}
              placement="rightBottom"
            >
              <img src={GrayTipIcon} alt="" className="tip-icon" />
            </Tooltip>

            {t("dappDeal.minerFees")}
          </div>
          <div className="value-text">{currentPriceObj.fee}</div>
        </div>
      </div>
      <div className="action-btn-box">
        <Button className="action-btn" type="primary" onClick={() => handleBtnClick()}>
          {headerType == 0 ? t("dappDeal.authorizedSubscription") : t("dappDeal.tabRedemption")}
        </Button>
      </div>
      <BuyDetailRecords ref={buyDetailRecordsRef}/>
      <SellDetailRecords ref={sellDetailRecordsRef}/>

    </div>
  );
})

export default DealBox;
